package com.smartthinking.CICPNL;

import java.util.ArrayList;
import java.util.Date;
import java.util.Dictionary;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.parse.ParseACL;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.smartthinking.CICPNL.home.activity.Splash2;
import com.smartthinking.CICPNL.home.activity.Utilities;


public class Chat extends Activity {
	private Dialog progressDialog;
	private List<ParseObject> todos;
	private EditText chat_text, chat_username;
	public String[] username, date, text;
	public Dialog dialog;
	public Button cancelar, continuar, actualizar;
	public String chat_user, chat_date, chat_texto;
	public static ArrayList<Dictionary<String,String>> Splash = null;

	public void voidFinish(View V) {
		finish();
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_activity_chat);
		
		//splash
		try{
			int EVEIDR = Utilities.EVE_IDR;
			String qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre = 'SPLASH CHAT' ORDER BY b.ban_nombre";
			Splash = Utilities.qry2(getApplicationContext(), qry);
			
	    	if(Splash.size()>0){
	    		Dictionary<String, String> dic = Splash.get(0);
		    	String strPoster = dic.get("ban_url").toString();
			    String strTimer = dic.get("ban_timer").toString();
			    String strPatrocinador = dic.get("pat_idr").toString();
			    if (strPoster.equals("null")) {
			        strPoster = "";
			    }
			    if(strPoster.length()>0){
					Intent intent = new Intent(this, Splash2.class);
					Bundle bund = new Bundle();
					bund.putString("PUT_IMG",strPoster);
					bund.putString("PUT_PAT",strPatrocinador);
					bund.putString("PUT_TIME",strTimer);
					intent.putExtras(bund);
					startActivity(intent);
			    }
		    }
		}catch(Exception ex){}
		
		dialog = new Dialog(Chat.this);
		dialog.setContentView(R.layout.ui_dialog_username);
		dialog.setTitle("Chat");
		chat_username = (EditText) dialog.findViewById(R.id.et_chat_username);
		cancelar = (Button) dialog.findViewById(R.id.btn_chat_cancelar);
		continuar = (Button) dialog.findViewById(R.id.btn_chat_continuar);
		actualizar = (Button) findViewById(R.id.bt_refresh);
		
		actualizar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new RemoteDataTask().execute();
			}
		});
		cancelar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				chat_user = "Chat name";
				dialog.dismiss();
				getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
			}
		});
		continuar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(chat_username.getText().toString().equals("")){
					Toast.makeText(getApplicationContext(), getResources().getString(R.string.msg_aviso_chat), Toast.LENGTH_LONG).show();
				}else{
					chat_user = chat_username.getText().toString();
					dialog.dismiss();
					getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
				}
			}
		});
		
		dialog.show();
		
		
		new RemoteDataTask().execute();

		chat_text = (EditText) findViewById(R.id.txt_chat);
		chat_text.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// If the event is a key-down event on the "enter" button
				if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
						(keyCode == KeyEvent.KEYCODE_ENTER)) {
					// Perform action on key press
					Date date = new Date();
					ParseObject testObject = new ParseObject("chatroom");
					testObject.put("text", ""+chat_text.getText().toString());
					testObject.put("userName", ""+chat_user);
					testObject.put("date", date);
					ParseACL postACL = new ParseACL(ParseUser.getCurrentUser());
					postACL.setPublicReadAccess(true);
					testObject.setACL(postACL);

					testObject.saveInBackground();
					InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

					imm.hideSoftInputFromWindow(chat_text.getWindowToken(), 0);
					chat_text.setText("");
					new RemoteDataTask().execute();
					
					return true;
				}
				return false;
			}
		});
		
		
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ui_activity_chat, menu);
		return true;
	}
	
	
	private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
		// Override this method to do custom remote calls
		protected Void doInBackground(Void... params) {
			// Gets the current list of todos in sorted order
			ParseQuery query = new ParseQuery("chatroom");
			query.orderByDescending("_created_at");

			try {
				todos = query.find();
				username = new String[todos.size()];
				date = new String[todos.size()];
				text = new String[todos.size()];
				for(int i = 0; i < todos.size(); i++){
					username[i] = todos.get(i).getString("userName");
					Date date2 = todos.get(i).getDate("date");
					
					date[i] = ""+date2.toString();
					text[i] = todos.get(i).getString("text");
					Log.i("username", ""+username[i]);
					Log.i("date", ""+date[i]);
					Log.i("text", ""+text[i]);


				}
				
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			Chat.this.progressDialog = ProgressDialog.show(Chat.this, "",getResources().getString(R.string.msg_cargando), true);
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Void... values) {

			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Void result) {
			try{
				ListView list_chat = (ListView) findViewById(R.id.list_chat);
				ChatArrayAdapter adapter = new ChatArrayAdapter();
				// Put the list of todos into the list view
//				ArrayAdapter<String> adapter = new ArrayAdapter<String>(Chat.this,
//						android.R.layout.simple_list_item_1);
				Log.i("todos size", ""+todos.size());

//				for (ParseObject todo : todos) {
//					Log.i("contenido", ""+todo.getString("text"));
////					adapter.add((String) todo.get("text"));
//				}
				list_chat.setAdapter(adapter);
				Chat.this.progressDialog.dismiss();
//				TextView empty = (TextView) findViewById(android.R.id.empty);
//				empty.setVisibility(View.VISIBLE);
			}catch (Exception e) {
				e.printStackTrace();
			}

		}
	}
	
	
	public class ChatArrayAdapter extends BaseAdapter {
		
		public ChatArrayAdapter() {
			// TODO Auto-generated constructor stub
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View rowView = null;
			try{
				LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				rowView = inflater.inflate(R.layout.ui_chat_item, parent, false);

				TextView date = (TextView) rowView.findViewById(R.id.txt_chat_date);
				date.setText(""+Chat.this.date[position]);
				date.setTextColor(Color.BLACK);

				TextView username = (TextView) rowView.findViewById(R.id.txt_chat_username);
				username.setText(""+Chat.this.username[position]);
				username.setTypeface(null,Typeface.BOLD);
				username.setTextColor(Color.BLACK);

				TextView texto = (TextView) rowView.findViewById(R.id.txt_chat_texto);
				texto.setText(""+Chat.this.text[position]);
				texto.setTextColor(Color.BLACK);
			}catch (Exception e) {
				e.printStackTrace();
			}
			

			return rowView;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return todos.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
	} 

}
